using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using S.M.SmartMedical.API.Read.Application.Query;
using S.M.SmartMedical.Domain.DTOs;
using S.M.SmartMedical.Domain.Entities;
using S.M.SmartMedical.ErrorCode;
using S.M.SmartMedical.Infrastructure.BaseRepository;

namespace S.M.SmartMedical.API.Read.Application.Handler
{
    /// <summary>
    /// 根据ID获取医院详情处理程序
    /// </summary>
    public class GetHospitalByIdHandler : IRequestHandler<GetHospitalByIdQuery, APIResult<HospitalDto>>
    {
        private readonly IRepository<Hospital> _hospitalRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetHospitalByIdHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        public GetHospitalByIdHandler(
            IRepository<Hospital> hospitalRepository,
            IMapper mapper,
            ILogger<GetHospitalByIdHandler> logger)
        {
            _hospitalRepository = hospitalRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理获取医院详情请求
        /// </summary>
        public async Task<APIResult<HospitalDto>> Handle(GetHospitalByIdQuery request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始查询医院详情，ID：{Id}", request.Id);

                var hospital = await _hospitalRepository.GetQueryable()
                    .FirstOrDefaultAsync(h => h.Id == request.Id && !h.IsDeleted, cancellationToken);

                if (hospital == null)
                {
                    _logger.LogWarning("未找到ID为 {Id} 的医院", request.Id);
                    return new APIResult<HospitalDto>
                    {
                        Code = APIEnum.Fail,
                        Message = "未找到该医院"
                    };
                }

                var hospitalDto = _mapper.Map<HospitalDto>(hospital);

                _logger.LogInformation("成功获取医院详情，ID：{Id}", request.Id);

                return new APIResult<HospitalDto>
                {
                    Code = APIEnum.OK,
                    Message = "查询成功",
                    Data = hospitalDto
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询医院详情时发生错误，ID：{Id}", request.Id);
                return new APIResult<HospitalDto>
                {
                    Code = APIEnum.Fail,
                    Message = "查询失败：" + ex.Message
                };
            }
        }
    }
}